import { getOpt } from "../tools.js";

import Select2Widget from './Select2Widget.js';
// globally assign select2 fn to $ element

import 'select2';

const Select2RemoteWidget = Select2Widget.extend({
    /*
     * A select2 widget using a remote data source
     *
     * Supports paginated results from an API with backbone-paginated style
     *
     * Share the API of SelectWidget
     *
     * @param url REST API endpoint URL
     * @param pageSize (optional) : how many to fech at once ?
     * @param extraUrlParams (optional) : key/value GET parameters for
     *   HTTP AJAX request.
     * @param value_label : the initial option label, corresponding to `value`arg
     *
     */

    initializePlaceHolder: function(placeholder, options) {
        /* Empty <option> is not required when using ajax datasource
         * we use this function to prefill initial option prior to any ajax
         * list request.
         */
        let initial_value = this.getOption('value');
        let initial_label = this.getOption('value_label');
        if (initial_value) {
            options[0] = {
                [this.id_key]: initial_value,
                [this.label_key]: initial_label
            };
        }
    },

    getSelect2Params: function() {
        let params = Select2Widget.prototype.getSelect2Params.apply(this);
        let pageSize = getOpt(this, 'pageSize', 50);
        let extraUrlParams = getOpt(this, 'extraUrlParams', {});
        let this_ = this;

        return Object.assign({}, params, {
            allowClear: true,
            ajax: {
                url: getOpt(this, 'url'),
                data: function (params) {
                    let baseURLParams = {
                        search: params.term,
                        // Respects backbone-paginated style:
                        page: params.page || 0,
                        items_per_page: pageSize,
                    };
                    return Object.assign({}, baseURLParams, extraUrlParams);
                },
                processResults: function (data, params) {
                    // Transforms backbone-paginated pagination style to
                    // select2 style
                    params.page = params.page || 0;
                    let totalCount = data[0].total_entries;
                    let thisPageReach = (params.page + 1) * pageSize;
                    return {
                        results: data[1].map(
                            x => ({id: x[this_.id_key], text: x[this_.label_key] })
                        ),
                        pagination: {
                            more: thisPageReach < totalCount,
                        }
                    };
                },
            },
        });
    },
});
export default Select2RemoteWidget;
